package com.qinggeng.project.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.enums.*;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.config.mq.MQSendUtils;
import com.qinggeng.framework.config.mq.dto.MessgaeBulletChatGoodsDetailDTO;
import com.qinggeng.framework.config.mq.enums.MQTypeEnum;
import com.qinggeng.framework.config.thread.ThreadPoolExecutorUtil;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.*;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.api.utils.EmojiUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.qinggeng.project.api.security.utils.ApiUtils.getIsLogin;

@Api(tags = "商品模块")
@RestController
@RequestMapping("${apiPath}/goods")
@Slf4j
@CrossOrigin
public class ApiGoodsController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiGoodsController.class);
    @Autowired
    private IGoodsClassifyService goodsClassifyService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IUserCollectService userCollectService;

    @Autowired
    private IUserCartService userCartService;

    @Autowired
    private IOrdersEvaluateService ordersEvaluateService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private IUserAddressService userAddressService;

    @Autowired
    private DistributionConfigService distributionConfigService;

    @Autowired
    private IUserSearchService searchService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrdersGoodsService ordersGoodsService;

    @Autowired
    private IShareService shareService;

    @Autowired
    private IGiftProbabilityService giftProbabilityService;

    @Autowired
    private MQSendUtils mqSendUtils;

    @Autowired
    private IUserGoodsLimitRecordService userGoodsLimitRecordService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IDistributionPointService pointService;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private IDistributionPointService distributionPointService;

    @Autowired
    private MemberService  memberService;

    @ApiOperation("商品分类")
    @GetMapping("/classifyList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "show", value = "显示类型 1=全部分类 2=首页分类", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "rank", value = "菜单等级 1=一级菜单 2=二级菜单", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "parentId", value = "父菜单id", dataType = "Integer", paramType = "query", required = false)
    })
    public AjaxResult classifyList(String show, Integer rank, Long parentId) {
        GoodsClassify where = new GoodsClassify();
        where.setVisible(StatusEnum.OK.getCode());
        where.setRank(rank);
        where.setParentId(parentId);

        if (show.equals("2")) {
            where.setIndexShow(StatusEnum.OK.getCode());
            where.setIsSpecial(0);
            List<GoodsClassify> goodsClassifies = goodsClassifyService.selectGoodsClassifyList(where);
           boolean bl= ApiUtils.getIsLogin()==false;
            log.info("会员专购检查登入状态 {}",bl);
           if (bl){
                goodsClassifies.removeIf(g ->"会员专购".equals(g.getClassifyName()));
            }else {
                long userId=ApiUtils.getUserId();
               log.info("会员专购 userId {}",userId);
               Integer type=memberService.isSVip(userId);
                if (MemberEnum.MEMBER.getKey().equals(type)==false){
                    goodsClassifies.removeIf(g ->"会员专购".equals(g.getClassifyName()));
                }
            }
            return AjaxResult.success(goodsClassifies);
        }
        if (show.equals("1")) {
            where.setIndexShow(StatusEnum.OK.getCode());
            where.setIsSpecial(0);
            List<GoodsClassify> goodsClassifies = goodsClassifyService.selectGoodsClassifyList(where);
            goodsClassifies.removeIf(goodsClassify -> "10".equals(goodsClassify.getIsActivity()));
            return AjaxResult.success(goodsClassifies);
        }

        return AjaxResult.error("参数不全");
    }

    @ApiOperation("商品列表")
    @GetMapping("/goodsList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", value = "搜索", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query", required = false),
            @ApiImplicitParam(name = "classifyId", value = "分类ID", dataType = "Long", paramType = "query", required = false),
            @ApiImplicitParam(name = "goodsMark", value = "商品标签 10.人气推荐 20.为你优选", dataType = "Long", paramType = "query", required = false),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "goodsTypes", value = "商品类型 10=普通商品 20=免费送 30=商家补贴 40=捶一捶商品", defaultValue = "10", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "lng", value = "经度", dataType = "Float", paramType = "query"),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Float", paramType = "query")
    })
    @LoginRequired(must = false, role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult goodsList(Long shopId, Long classifyId, Long goodsId, String goodsMark, String goodsTypes, String search,Float lng,Float lat) {
        try {
            if (shopId == null) {
                return AjaxResult.error("商户ID不存在");
            }

            //添加用户搜索记录
            if (getIsLogin() && StringUtils.isNotEmpty(search)) {
                String result = EmojiUtils.filter(search);
                searchService.insertSearch(ApiUtils.getUserId(), result);
            }

            startPage();
            Goods where = new Goods();
            where.setShopId(shopId);
            //推荐
            Long recommend = 1L;
            if (!recommend.equals(classifyId)) {
                where.setClassifyId(classifyId);
            }

            where.setGoodsId(goodsId);
            where.setGoodsMark(goodsMark);
            String[] types = null;
            if (!StringUtils.isEmpty(goodsTypes)) {
                types = goodsTypes.split(",");
                where.setGoodsTypes(types);
            }
            if (!StringUtils.isEmpty(search)) {
                where.setGoodsName(search);
            }
            List<GoodsDto> goodsDtoList = goodsService.selectGoodsListDto1(where);

            String pointName=pointService.getDistributionPointName(shopId,lng,lat);
            for (GoodsDto goodsDto : goodsDtoList) {

                if (goodsDto.getGoodsType().equals("50")) {
                    int popularity = Integer.parseInt(goodsDto.getPopularity());
                    String popularityString = intChange2Str(popularity);
                    goodsDto.setPopularity(popularityString);

                    int wantValue = (int) (goodsDto.getKeepNum() * 1.5);
                    String wantValueString = intChange2Str(wantValue);
                    goodsDto.setWantValue(wantValueString);

                    goodsDto.setStartDateStamp(goodsDto.getStartDate().getTime() + "");
                    goodsDto.setPickDateStamp(goodsDto.getPickDate().getTime() + "");
                }
                if(StringUtils.isNotEmpty(pointName)){
                    goodsDto.setSupplier(pointName);
                }
            }
            String filterGoodsType = "40";
            goodsDtoList = goodsDtoList.stream().filter(s -> !filterGoodsType.equals(s.getGoodsType())).collect(Collectors.toList());

            //获取用户购物车信息，设置商品加入购物车的数量
            if (getIsLogin()) {
                goodsDtoList = goodsService.setGoodsDtoFromUserCart(goodsDtoList, shopId, ApiUtils.getUserId());
            }

            ShareDto shareDto = null;
            if (types !=null && types.length >0){
                shareDto = shareService.selectShareDtoByType(types[0]);
            }

            goodsService.shareInformation(shareDto,goodsDtoList);
            try {
                if (recommend.equals(classifyId)) {
                    List<GoodsDto> goodsDtos = goodsService.recommendGoodsOrder(goodsDtoList, classifyId);

                    return AjaxResult.success(goodsDtos);
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                e.printStackTrace();
            }

            try {
                //特价商品
                String goodsType = "30";
                if (goodsType.equals(goodsTypes)){
                    List<String> colorList = JSONArray.parseArray((String) sysConfigService.selectConfigByKey("sys.goods.backgroundColor"), String.class);
                    if (CollectionUtils.isEmpty(colorList)){
                        throw new CustomException("colorList is null");
                    }
                    int count = 0;
                    for (GoodsDto goodsDto : goodsDtoList) {
                        if (count>3){
                            count = 0;
                        }
                        goodsDto.setColor(colorList.get(count));
                        count ++;
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                e.printStackTrace();
            }

            //打乱顺序
            Collections.shuffle(goodsDtoList);
            return AjaxResult.success(goodsDtoList);
        } catch (Exception e) {
            log.error("goods.goodsList()={}", e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("系统繁忙");
        }
    }

    //单位转换
    private String intChange2Str(int number) {
        String str = "";
        if (number <= 0) {
            str = "";
        } else if (number < 10000) {
            str = number + "";
        } else {
            double d = (double) number;
            double num = d / 10000;//1.将数字转换成以万为单位的数字

            BigDecimal b = new BigDecimal(num);
            double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();//2.转换后的数字四舍五入保留小数点后一位;
            str = f1 + "万";
        }
        return str;
    }

    @ApiOperation("一级分类商品列表")
    @GetMapping("/goodsListForOne")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", value = "搜索", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "classifyId", value = "分类ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "goodsMark", value = "商品标签 10.人气推荐 20.为你优选", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "goodsType", value = "商品类型 10=普通商品 20=免费送 30=商家补贴", defaultValue = "10", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序", defaultValue = "1", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "经度", dataType = "Float", paramType = "query"),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Float", paramType = "query")
    })
    @LoginRequired(must = false, role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult goodsListForOne(
            Long shopId,
            Long goodsId,
            Long classifyId,
            String goodsMark,
            String search,
            Float lng,
            Float lat,
            @RequestParam(defaultValue = "10") String goodsType
    ) {
        if (shopId == null) {
            return AjaxResult.error("商户ID不存在");
        }
        goodsMark = "";
        //添加用户搜索记录
        if (getIsLogin() && StringUtils.isNotEmpty(search)) {
            String result = EmojiUtils.filter(search);
            searchService.insertSearch(ApiUtils.getUserId(), result);
        }
        startPage();
        Goods where = new Goods();
        where.setShopId(shopId);
        where.setClassifyId(classifyId);
        where.setGoodsId(goodsId);
        where.setGoodsMark(goodsMark);
        where.setGoodsType(goodsType);
        if (StringUtils.isNotEmpty(search)) {
            where.setGoodsName(search);
        }
        List<GoodsDto> goodsDtoList = goodsService.selectGoodsListDtoForOne(where);
        ShareDto shareDto = shareService.selectShareDtoByType(goodsType);
        goodsService.shareInformation(shareDto,goodsDtoList);
        String pointName=pointService.getDistributionPointName(shopId,lng,lat);
        for (GoodsDto goodsDto:goodsDtoList
             ) {
            if(StringUtils.isNotEmpty(pointName)){
                goodsDto.setSupplier(pointName);
            }
        }
        //获取用户购物车信息，设置商品加入购物车的数量
        if (getIsLogin()) {
            goodsDtoList = goodsService.setGoodsDtoFromUserCart(goodsDtoList, shopId, ApiUtils.getUserId());
        }
        //打乱顺序
        Collections.shuffle(goodsDtoList);
        return AjaxResult.success(goodsDtoList);
    }

    @ApiOperation("商品详情")
    @GetMapping("/goodsInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "lng", value = "经度", dataType = "Float", paramType = "query", required = true),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Float", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = false)
    })
    @CrossOrigin
    @LoginRequired(must = false, role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult goodsInfo(Long goodsId, Long shopId, Float lng, Float lat,String isChief) {
        Shop shop = shopService.selectShopById(shopId);
        if (shop == null) {
            return AjaxResult.error("商户不存在");
        }
        Map<String, Object> data = Maps.newHashMap();
        try {

            GoodsInfoDto goodsInfoDto = goodsService.selectGoodsDtoById(goodsId, shopId);
            //如果商品状态为10=已下架
            if (null == goodsInfoDto || goodsInfoDto.getStatus().equals(CommonEnum.STATUS_10.getValue())) {
                return AjaxResult.error("商品已下架！", ShowTypeEnum.用户.getValue());
            }
            //预售
            if (goodsInfoDto.getGoodsType().equals("50")) {
                int popularity = Integer.parseInt(goodsInfoDto.getPopularity());
                String popularityString = intChange2Str(popularity);
                goodsInfoDto.setPopularity(popularityString);

                int wantValue = (int) (goodsInfoDto.getKeepNum() * 1.5);
                String wantValueString = intChange2Str(wantValue);
                goodsInfoDto.setWantValue(wantValueString);

                goodsInfoDto.setStartDateStamp(goodsInfoDto.getStartDate().getTime() + "");
                goodsInfoDto.setPickDateStamp(goodsInfoDto.getPickDate().getTime() + "");
            }

            UserCollect userCollect = null;
            UserAddress userAddress = null;
            Future<UserCollect> future2 = null;
            Future<UserAddress> future3 = null;
            ThreadPoolExecutor threadPoolExecutor = ThreadPoolExecutorUtil.getPoll();
            if (getIsLogin()) {
                Long userId = ApiUtils.getUserId();
                future2 = threadPoolExecutor.submit(() -> {
                    UserCollect userCollectThread = userCollectService.selectUserCollectByUserId(goodsId, shopId, userId);
                    return userCollectThread;
                });
                future3 = threadPoolExecutor.submit(() -> userAddressService.selectUserAddressByUserId(userId, shopId));

            }
            Future<String> future4 = threadPoolExecutor.submit(() -> {
                String distDateTime = distributionConfigService.getDistDateTime();
                return distDateTime;
            });
            Future<Shop> future5 = threadPoolExecutor.submit(() -> {
                Shop shop1 = shopService.selectShopById(goodsInfoDto.getShopId());
                return shop1;
            });
            Future<ShareDto> future6 = threadPoolExecutor.submit(() -> {
                ShareDto shareDto = shareService.selectShareDtoByType(goodsInfoDto.getGoodsType());
                return shareDto;
            });

            Future<GiftProbability> future7 = threadPoolExecutor.submit(() -> {
                GiftProbability giftProbability = giftProbabilityService.selectHelpNumByGoodsPrice(goodsInfoDto.getGroupPrice());
                return giftProbability;
            });

            if (getIsLogin()) {
                if (future2 == null) {
                    throw new CustomException("获取用户信息异常");
                }
                userCollect = future2.get();
                userAddress = future3.get();
            }
            String distDateTime = future4.get();
            Shop shop1 = future5.get();
            ShareDto shareDto = future6.get();
            GiftProbability giftProbability = future7.get();

            //限购数量
            goodsInfoDto.setLimitNum(userGoodsLimitRecordService.getUserGoodsLimitRemainNum(goodsId));
            data.put("info", goodsInfoDto);

            if (getIsLogin()) {
                if (userCollect == null) {
                    userCollect = new UserCollect();
                    userCollect.setStatus("20");
                }
                data.put("collect", userCollect);

                data.put("defaultAddress", userAddress);
            } else {
                UserCollect userCollectNotLOgin = new UserCollect();
                userCollectNotLOgin.setStatus("20");
                data.put("collect", userCollectNotLOgin);
            }

            data.put("defaultTime", distDateTime);

            data.put("shop", shop1);

            try {
                if (shareDto != null) {
                    data.put("title", "【¥" + goodsInfoDto.getGroupPrice() + "】" + shareDto.getTitle() + goodsInfoDto.getGoodsName());
                    data.put("subtitle", "【¥" + goodsInfoDto.getGroupPrice() + "】" + shareDto.getSubtitle());
                    if (!StringUtils.isEmpty(isChief) && ChiefJudgmentEnum.YES.getValue().equals(isChief)&&ApiUtils.getIsLogin()){
                        Long courierId = sysUserService.selectUserIdByPhoneNumberAndUserType(ApiUtils.getApiUser().getUser().getPhonenumber(), UserTypeEnum.COURIER.getCode());
                        DistributionPoint distributionPoint = distributionPointService.selectPointByCourierId(courierId);
                        if (distributionPoint == null){
                            throw new CustomException("ApiGoodsController goodsInfo() distributionPoint is null");
                        }
                        data.put("title", shareDto.getHeadShare().replace("$",distributionPoint.getPointName())+"【¥" + goodsInfoDto.getGroupPrice() + "】" + shareDto.getTitle()+ goodsInfoDto.getGoodsName());
                        data.put("subtitle", shareDto.getHeadShare().replace("$",distributionPoint.getPointName())+"【¥" + goodsInfoDto.getGroupPrice() + "】" + shareDto.getTitle() + goodsInfoDto.getGoodsName());
                    }
                } else {
                    data.put("title", "【¥" + goodsInfoDto.getGroupPrice() + "】" + goodsInfoDto.getGoodsName());
                    data.put("subtitle", "【¥" + goodsInfoDto.getGroupPrice() + "】"  + goodsInfoDto.getGoodsName());
                    if (!StringUtils.isEmpty(isChief) && ChiefJudgmentEnum.YES.getValue().equals(isChief)&&ApiUtils.getIsLogin()){
                        Long courierId = sysUserService.selectUserIdByPhoneNumberAndUserType(ApiUtils.getApiUser().getUser().getPhonenumber(), UserTypeEnum.COURIER.getCode());
                        DistributionPoint distributionPoint = distributionPointService.selectPointByCourierId(courierId);
                        if (distributionPoint == null){
                            throw new CustomException("ApiGoodsController goodsInfo() distributionPoint is null");
                        }
                        data.put("title", distributionPoint.getPointName()+"【¥" + goodsInfoDto.getGroupPrice() + "】" + goodsInfoDto.getGoodsName());
                        data.put("subtitle", distributionPoint.getPointName()+"【¥" + goodsInfoDto.getGroupPrice() + "】"  + goodsInfoDto.getGoodsName());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("goodsInfo() is error",e);
            }


            //助力次数
            if (giftProbability == null) {
                return AjaxResult.error("助力次数不存在");
            }
            data.put("help_num", "" + giftProbability.getHelpNum());
            //发送弹幕
            if (ApiUtils.getIsLogin()) {
                MessgaeBulletChatGoodsDetailDTO detailDTO = new MessgaeBulletChatGoodsDetailDTO();
                detailDTO.setType(MQTypeEnum.GOODS_DETAI.getType());
                detailDTO.setUserId(ApiUtils.getUserId());
                detailDTO.setGoodsId(goodsId);
                mqSendUtils.sendAsynMessage(detailDTO);
            }
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("goodsInfo()" + e.getMessage(), e);
            return AjaxResult.error("系统异常");
        }
    }

    @ApiOperation("添加商品收藏")
    @PostMapping("/addCollect")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult addCollect(Long goodsId, Long shopId) {
        GoodsInfoDto goodsInfoDto = goodsService.selectGoodsDtoById(goodsId, shopId);
        if (goodsInfoDto == null) {
            return AjaxResult.error("商品不存在");
        }
        UserCollect userCollect = userCollectService.selectUserCollectByUserId(goodsId, shopId, ApiUtils.getUserId());
        if (userCollect == null) {
            userCollect = new UserCollect();
            userCollect.setUserId(ApiUtils.getUserId());
            userCollect.setGoodsId(goodsId);
            userCollect.setShopId(shopId);
            return toAjax(userCollectService.insertUserCollect(userCollect));
        } else {
            if (userCollect.getStatus().equals("10")) {
                return AjaxResult.error("已收藏");
            } else {
                userCollect.setStatus("10");
                return toAjax(userCollectService.updateUserCollect(userCollect));
            }
        }
    }

    @ApiOperation("取消收藏")
    @PostMapping("/cancelCollect")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult cancelCollect(Long goodsId, Long shopId) {
        if (goodsService.selectGoodsDtoById(goodsId, shopId) == null) {
            return AjaxResult.error("商品不存在");
        }
        UserCollect userCollect = userCollectService.selectUserCollectByUserId(goodsId, shopId, ApiUtils.getUserId());
        if (userCollect == null) {
            return AjaxResult.error("无收藏信息");
        }
        userCollect.setStatus("20");
        return toAjax(userCollectService.updateUserCollect(userCollect));
    }

    @ApiOperation("加入购物车")
    @PostMapping("/addCart")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "goodsNum", value = "商品数量", dataType = "int", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult addCart(AddCartDTO dto) {
        //用户购物车所有商品的数量
        Map<String, Object> data = Maps.newHashMap();
        dto.setUserId(ApiUtils.getUserId());
        data.put("goodsNum", userCartService.addCart(dto));
        return AjaxResult.success("加入成功", data);
    }

    @ApiOperation("再来一单")
    @PostMapping("/addAgain")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ordersId", value = "订单ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult addAgain(Long ordersId) {
        Orders orders = ordersService.selectOrdersById(ordersId);
        if (null == orders) {
            return AjaxResult.error("订单不存在");
        }
        if (orders.getOrdersType().equals(CommonEnum.STATUS_20.getValue())) {
            return AjaxResult.error("免费商品，无法再来一单", ShowTypeEnum.用户.getValue());
        }
        //根据订单号查询订单商品
        List<OrdersGoods> ordersGoodsList = ordersGoodsService.selectOrderGoodListByOrdersId(ordersId);
        if (CollectionUtils.isEmpty(ordersGoodsList)) {
            return AjaxResult.error("再来一单商品列表不能为空");
        }
        //添加成功数量
        int addCount = 0;
        //未添加成功商品集合（已被抢光或已下架）
        List<OrdersGoods> notAddList = new ArrayList<>();
        for (OrdersGoods ordersGoods : ordersGoodsList) {
            AddCartDTO addCartDTO = new AddCartDTO();
            addCartDTO.setGoodsId(ordersGoods.getGoodsId());
            addCartDTO.setShopId(orders.getShopId());
            addCartDTO.setGoodsNum(ordersGoods.getGoodsNum());
            addCartDTO.setUserId(ApiUtils.getUserId());
            try {
                userCartService.addCart(addCartDTO);
                addCount++;
            } catch (Exception e) {
                notAddList.add(ordersGoods);
            }
        }
        //用户购物车所有商品的数量
        Map<String, Object> data = Maps.newHashMap();
        data.put("goodsNum", userCartService.selectUserCartGoodsNumByUserId(ApiUtils.getUserId()));
        if (addCount == 0) {
            return AjaxResult.error("所有商品已被抢光，无法再来一单！", ShowTypeEnum.用户.getValue());
        }
        if (notAddList.size() > 0) {
            return AjaxResult.error(notAddList.size() + "款商品已下架、已被抢光或已达限购份额，已为您添加其它商品！", ShowTypeEnum.用户.getValue(), data);
        }
        return AjaxResult.success("再来一单成功", ShowTypeEnum.后台.getValue(), data);
    }


    @ApiOperation("评价列表")
    @GetMapping("/evaluateList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "goodsId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
    })
    @CrossOrigin
    public AjaxResult evaluateList(Long goodsId, Long shopId) {
        startPage();
        OrdersEvaluate where = new OrdersEvaluate();
        where.setGoodsId(goodsId);
        where.setShopId(shopId);
        return AjaxResult.success(ordersEvaluateService.selectOrdersEvaluateGoodsDtoList(where));
    }

    @ApiOperation("商品属性spu")
    @GetMapping("/goodsSpu")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mainCategory", value = "商品名", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "shopId", value = "商户ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "classifyId", value = "分类id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "goodsMark", value = "商品标签", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "goodsType", value = "商品类型", dataType = "String", paramType = "query", required = true),
    })
    public AjaxResult goodsSpu(Long mainCategory, Long shopId, Long classifyId, String goodsMark, @RequestParam(defaultValue = "10") String goodsType) {
        List<GoodsDto> goodsDtoList = null;
        ArrayList<GoodsInfoDto> goodsInfoDtoList = null;
        if (mainCategory == null || mainCategory <= 0) {

            return AjaxResult.error("无数据", goodsDtoList = Lists.newArrayList());
        }
        try {
            if (shopId == null) {
                LOGGER.info("商户Id不存在，shopId = null");
                return AjaxResult.error("商户ID不存在");
            }
            Goods where = new Goods();
            where.setMainCategory(mainCategory);
            where.setShopId(shopId);
            where.setClassifyId(classifyId);
            where.setGoodsMark(goodsMark);
            where.setGoodsType(goodsType);
            goodsDtoList = goodsService.selectGoodsSkuList(where);
            if (goodsDtoList == null || goodsDtoList.size() == 0) {
                goodsDtoList = Lists.newArrayList();
            }
            goodsInfoDtoList = Lists.newArrayList();
            for (GoodsDto goodsDto : goodsDtoList) {
                GoodsInfoDto goodsInfoDto = goodsService.selectGoodsDtoById(goodsDto.getGoodsId(), goodsDto.getShopId());
                goodsInfoDtoList.add(goodsInfoDto);
            }
            Collections.sort(goodsInfoDtoList, (GoodsInfoDto g1, GoodsInfoDto g2) -> {
                int num = g1.getGroupPrice().intValue() - g2.getGroupPrice().intValue();
                return num;
            });
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("查询商品属性出错");
            return AjaxResult.error("查询商品属性出错");
        }
        return AjaxResult.success(goodsInfoDtoList);
    }

    @ApiOperation("推荐商品")
    @GetMapping("/recomGoods")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "商户Id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
    })
    public AjaxResult recomGoods(Long shopId) {
        if (shopId == null) {
            return AjaxResult.error("商户ID不存在");
        }
        startPage();
        Goods where = new Goods();
        where.setShopId(shopId);
        //人气推荐
        where.setGoodsMark("10");
        //普通商品
        where.setGoodsType("10");
        //查询商品
        List<GoodsDto> goodsDtoList = goodsService.selectGoodsListDto(where);
        Collections.shuffle(goodsDtoList); //打乱顺序

        return AjaxResult.success(goodsDtoList);

    }


    @ApiOperation("商品购买记录")
    @GetMapping("/buyRecord")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品Id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
    })
    public AjaxResult buyRecord(Long goodsId) {
        Goods goods = goodsService.selectGoodsById(goodsId);
        if (null == goods) {
            return AjaxResult.error("商品不存在");
        }
        Map<String, Object> data = Maps.newHashMap();
        data.put("userNum", ordersGoodsService.getBuyUserNumByMainCategory(goods.getMainCategory()));
        data.put("saleNum", ordersGoodsService.getOrdersGoodsNumByMainCategory(goods.getMainCategory()));
        startPage();
        List<OrdersUserDto> userDtoList = ordersGoodsService.listOrdersUserDto(goods.getMainCategory());
        data.put("userList", userDtoList);
        return AjaxResult.success(data);
    }
    //跳转批发
    @GetMapping("/jumpToWholesale")
    public AjaxResult jumpToWholesale(Long wholeGoodsId){
        try {
            if (wholeGoodsId == null || wholeGoodsId == 0){
                throw new CustomException("wholeGoodsId is null");
            }
            Goods goods = goodsService.selectGoodsById(wholeGoodsId);
            if (goods == null){
                throw new CustomException("goods is null");
            }
            GoodsClassify where = new GoodsClassify();
            where.setVisible(StatusEnum.OK.getCode());
            where.setRank(1);
            where.setIndexShow(StatusEnum.OK.getCode());
            where.setIsSpecial(0);
            List<GoodsClassify> goodsClassifies = goodsClassifyService.selectGoodsClassifyList(where);
            if (CollectionUtils.isEmpty(goodsClassifies)){
                throw new CustomException("goodsClassifies is null");
            }
            GoodsClassify goodsClassify = goodsClassifyService.selectGoodsClassifyById(goods.getClassifyId());
            if (goodsClassify == null){
                throw new CustomException("goodsClassify is null");
            }
            HashMap<String, Object> data = Maps.newHashMap();
            data.put("goodsId",goods.getGoodsId().toString());
            data.put("classifyId",goodsClassify.getParentId());
            data.put("goodsClassifies",goodsClassifies);
            return AjaxResult.success(data);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new CustomException(e.getMessage());
        }
    }

    /*//VPI购买
    @GetMapping("/vips")
    public AjaxResult vips(){
        List<Goods> goodsList=goodsService.selectGoodsListDtoForOneByGoodsIds();
        return AjaxResult.success(goodsList);
    }*/
}
